const { seriesModel, chapterModel, userModel, stuModel } = require('../../model');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const { getResultToObject } = require('../../services/utils');

module.exports = {
  list: function (req,res) {
    const { org, account } = req.decode;
    const series_attr = [
      'id',
      'order',
      'type',
      'name',
      'createdAt'
    ];

    userModel.findByRelation(['org'], {
      org: org,
      account: account
    },{
      model: seriesModel.getModel(),
      attributes: series_attr
    })
      .then(result => {
        const list = getResultToObject(result, 'series', series_attr);
        res.send({
          code: 20000,
          data: {
            items: list,
            total: list.length
          }
        });
      }).catch(err => {
        console.log(err);
        res.send({
          code: 10000,
          message: '获取系列失败'
        });
      })
  },
  create: function (req,res) {
    const { org } = req.decode;
    const { total, name, type } = req.body;

    seriesModel.create({
      order: total + 1,
      org: org,
      name: name,
      type: type,
      updatedAt: Date.now(),
      createdAt: Date.now()
    })
      .then(() => {
        res.send({
          code: 20000
        })
      })
      .catch(err => {
        console.log(err);
        res.send({
          code: 10000
        })
      })
  },
  delete: async (req,res) => {
    const { org } = req.decode;
    const { id, order } = req.body;

    try {
      const chapterExist = await chapterModel.findByFilter(['id'], {series: id});
      if (chapterExist) {
        return res.send({
          code: 10000, msg: `该系列还存在${chapterExist.length}个章节，请先删除章节`
        })
      }
      await seriesModel.delete({id: id, org: org});
      await seriesModel.decrement('order',{org: org, order:{[Op.gt]: order}});
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.log(e);
      return res.send({
        code: 10000,
        message: '系列删除失败'
      });
    }
  },
  update: function (req,res) {
    const { org } = req.decode;
    const { id, name } = req.body;
    const attributes = { name: name };
    const where = { id: id, org: org };
    seriesModel.update(attributes,where).then(function () {
      res.send({
        code: 20000
      })
    }).catch(function (err) {
      console.log(err);
      res.send({
        code: 10000
      })
    })
  },
  order: function (req,res) {
    const org = req.decode.org;
    const { current, target, curOrder, tarOrder } = req.body;

    seriesModel.update({ order: curOrder }, { id: current, org: org })
      .then(function (result) {
        seriesModel.update({ order: tarOrder }, { id: target, org: org }).then(function () {
          return res.send({
            code: 20000
          })
        })
      })
  }
};
